'use strict';



angular.module('myApp.hosts_list', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/testing/hosts_list', {
            templateUrl: 'pages/testing/hosts_comm/hosts_list.html',
            controller: 'HostsListCtrl'
        });
    }])

    .controller('HostsListCtrl', function ($scope, $http, $location, $rootScope, $filter) {
        $rootScope.show_header = true
        $rootScope.show_footer = true
        $rootScope.title = '主机通信'
        console.log($location.path(), ' entered')



        $rootScope.localMenus[$location.path()] = [
            {
                text: '刷新主机列表',
                callback: async () => {
                    swal.fire({
                        title: $filter('translate')("正在刷新"),
                        text: $filter('translate')("请稍等"),
                        // icon: "/images/loading.gif",
                        button: false,
                        closeOnClickOutside: false,
                        closeOnEsc: false
                    });
                    await $http.get('/system/clear_hosts')
                    setTimeout(() => {
                        updateHostsList()
                        swal.close()
                    }, 1500)
                }
            },
        ]

        const updateHostsList = () => {
            $http.get('/system/hosts_list').then(res => {

                let hosts = res.data
                $rootScope.items = hosts.map((item, i) => {
                    let msg_count = $rootScope.msgs.filter(msg => msg.from == item || msg.to == item).length
                    return {
                        id: i,
                        ip: item,
                        msg_count: msg_count,
                        link: encodeURI(`/app/#!/testing/hosts_comm?host=${item}`)
                    }
                })

                $rootScope.rowNum = 8
                $rootScope.colNum = 1
                $rootScope.updatePageInfo()

                // ngRefresh()
            }, (err) => {
                console.log(err)
            })
        }

        $rootScope.onNewMsg = (msg) => {
            if ($location.path() == '/testing/hosts_list') {
                updateHostsList()
                if (msg.msg && msg.from != 'localhost') {
                    swal.fire({
                        title: translate("新消息"),
                        text: `${msg.from}:\n${msg.msg}`,
                        // showConfirmButton: true,
                        showCancelButton: true,
                        cancelButtonText: "关闭",
                    });
                }
            }
        }

        updateHostsList()
    });

